<template>
  <div id="productManager">
    <!-- <h3>product-manager页面</h3> -->
    <!-- 按钮 搜索框 -->
    <div class="productManager_top">
      <el-col :span="2">
        <el-button type="primary" @click="addProduct">添加</el-button>
      </el-col>
      <el-col :span="4">
        <el-input v-model="input" placeholder="请输入产品名称" class="productName" />
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="search">查询</el-button>
      </el-col>
    </div>
    <!-- 表格 -->
    <div class="productManager_center">
      <el-table :data="productList" stripe style="width: 100%">
        <el-table-column prop="id" label="编号" width="180" align="center" />
        <el-table-column prop="name" label="产品名称" align="center" />
        <el-table-column prop="price" label="价格" align="center" />
        <el-table-column prop="description" label="产品描述" align="center" />
        <el-table-column prop="categoryName" label="所属产品" align="center" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="delById(scope.$index,scope.row)">删除</el-button>
            <el-button type="text" size="small" @click="changeProduct(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="details(scope.row.id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页按钮 -->
    <div class="productManager_footer">
      <el-pagination :current-page.sync="currentPage1" :page-size="pageSize" layout="total, prev, pager, next" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 添加/修改 模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="myform" :model="form" :rules="rules" label-width="100px" class="demo-form">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="所属栏目" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择所属栏目">
            <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品介绍">
          <el-input v-model="form.description" type="textarea" placeholder="请输入产品介绍" />
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary">点击上传</el-button>
          <br>
          <span style="font-size:12px">只能上传jpg/png文件，且不超过500kb</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('myform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'querystring' // 将json数据转化为查询字符串
export default {
  data() {
    return {
      input: '',
      products: [],
      total: 0,
      currentPage1: 1,
      pageSize: 6, // 页面大小
      categorys: [], // 所有栏目信息
      title: '添加产品信息',

      dialogFormVisible: false,
      form: {
        name: '',
        categoryId: '',
        description: '',
        price: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入产品名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择所属栏目', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字值', trigger: 'blur' }
        ]
      }// rules结束
    }
  },
  computed: {
    list() {
      return this.$store.getters.list
    },
    // 将categoryId转化为所属栏目name
    productList: function() {
      var self = this
      // var filterList=[];
      // 1.获取所有产品信息
      // console.log(this.products);
      // 2.获取所有栏目信息
      // console.log(this.categorys,'cate');
      // 3.用一个产品的id匹配所有栏目id,,找到相同id对象,将栏目对象中name赋值给产品对象
      this.products.forEach((item) => {
        // item->产品对象  item.categoryId
        for (var i = 0; i < self.categorys.length; i++) {
          // categorys[i]:每一个栏目对象
          if (item.categoryId == self.categorys[i].id) {//eslint-disable-line
            // console.log(self.categorys[i])
            item.categoryName = self.categorys[i].name
            // filterList.push(item);
          }
          // console.log(item);
        }
      })
      return this.products
    }
  },
  created() {
    this.findAllCategorys().then(res => {
      // 所有栏目查询完成
      this.categorys = res.data.data
      this.findAll()// 查询所有产品
    })
  },
  methods: {
    // 给详情按钮绑定事件
    details(id) {
      // alert(id);
      this.$router.push({ path: '/product-details/index', query: { id: id }})
    },
    // 给确定按钮绑定事件
    submitForm(formName) {
      var self = this
      // 1.获取表单数据+表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          // 2.发送请求
          self.$axios.post('/product/saveOrUpdate', qs.stringify(self.form)).then(res => {
            if (res.data.status == 200) {//eslint-disable-line
              // 保存成功

              self.$message({
                message: '恭喜你，保存成功',
                type: 'success'
              })
              self.findAll()
            } else {
              // 保存失败
              self.$message.error('保存失败')
            }
            self.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 给添加按钮绑定事件
    addProduct() {
      this.dialogFormVisible = true
      this.title = '添加产品信息'
      this.form = {
        name: '',
        categoryId: '',
        description: '',
        price: ''
      }
    },
    // 给修改按钮绑定事件
    changeProduct(row) {
      this.dialogFormVisible = true
      this.title = '修改订单信息'
      // console.log(row)
      this.form = {
        id: row.id,
        name: row.name,
        price: row.price,
        categoryId: row.categoryId,
        description: row.description
      }
    },
    // 点击搜索按钮，触发搜索函数
    search() {
      // 1.获取用户输入内容
      // alert(this.input)
      if (this.input) {
        this.findAll(this.input)
      } else {
        this.findAll()
      }
    },
    // 封装查询所有栏目的函数
    findAllCategorys() {
      return this.$axios.get('/category/findAll')
    },
    // 分页按钮的函数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage1 = val
      this.findAll()
    },
    // 分页查询封装函数
    findAll(name) {
      if (name) {
        // 点击的是搜索
        var data = {
          page: this.currentPage1 - 1,
          pageSize: this.pageSize,
          name: name
        }
      } else {
        // 非搜索
        var data = {//eslint-disable-line
          page: this.currentPage1 - 1,
          pageSize: this.pageSize
        }
      }

      this.$axios.post('/product/query', qs.stringify(data)).then(response => {
        // console.log(response);
        this.products = response.data.data.list
        this.total = response.data.data.total
      })
    },
    // 根据id删除单条数据
    delById(index, row) {
      var id = row.id
      var self = this
      // console.log(index,row)   //index为第几行   row为当前行的数据
      this.$confirm('此操作将永久删除这条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户确认删除
        self.$axios.get('/product/deleteById', {
          params: { id }
        }).then((response) => {
          if (response.data.status == 200) {//eslint-disable-line
            // 删除成功
            self.$message({
              type: 'success',
              message: '删除成功!'
            })
            self.findAll()
          } else {
            // 删除失败
            self.$message({
              showClose: true,
              message: '删除失败',
              type: 'error'
            })
          }
        })
      }).catch(() => {
        self.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }

}
</script>
<style lang='scss' scoped>
    #productManager{
        padding: 20px;
        .productName{
            padding-right: 20px;
        }
    }

</style>
